const bcrypt = require('bcryptjs');
const db = require('../config/database');
const { generateToken } = require('../middleware/jwtAuth');
const logger = require('../utils/logger');
const smsService = require('../services/smsService');
const verificationCodeService = require('../services/verificationCodeService');

class UserAuthController {
  // 用户账号密码注册
  async register(req, res) {
    try {
      const { username, password, phone, nickname } = req.body;

      // 参数验证
      if (!username || !password || !phone) {
        return res.json({
          success: false,
          message: '用户名、密码和手机号不能为空'
        });
      }

      // 验证用户名格式
      if (!/^[a-zA-Z0-9_]{4,20}$/.test(username)) {
        return res.json({
          success: false,
          message: '用户名格式不正确，应为4-20位字母、数字或下划线'
        });
      }

      // 验证密码长度
      if (password.length < 6) {
        return res.json({
          success: false,
          message: '密码长度不能少于6位'
        });
      }

      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        return res.json({
          success: false,
          message: '手机号格式不正确'
        });
      }

      // 检查用户名是否已存在
      const [existingUsers] = await db.query(
        'SELECT id FROM users WHERE username = ? OR phone = ?',
        [username, phone]
      );

      if (existingUsers.length > 0) {
        return res.json({
          success: false,
          message: '用户名或手机号已被注册'
        });
      }

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10);

      // 创建用户
      const [result] = await db.query(
        `INSERT INTO users (username, password, phone, nickname, status, created_at, updated_at) 
         VALUES (?, ?, ?, ?, 1, NOW(), NOW())`,
        [username, hashedPassword, phone, nickname || username]
      );

      const userId = result.insertId;
      const token = generateToken(userId);

      logger.success('用户注册成功', { username, userId });

      res.json({
        success: true,
        message: '注册成功',
        data: {
          token,
          user: {
            id: userId,
            username,
            nickname: nickname || username,
            phone
          }
        }
      });
    } catch (error) {
      logger.error('用户注册失败', { error: error.message });
      res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }

  // 用户账号密码登录
  async login(req, res) {
    try {
      const { username, password } = req.body;

      if (!username || !password) {
        return res.json({
          success: false,
          message: '用户名和密码不能为空'
        });
      }

      // 查询用户（支持用户名或手机号登录）
      const [users] = await db.query(
        'SELECT id, username, password, nickname, phone, avatar, status FROM users WHERE (username = ? OR phone = ?) AND is_guest = 0',
        [username, username]
      );

      if (users.length === 0) {
        return res.json({
          success: false,
          message: '用户名或密码错误'
        });
      }

      const user = users[0];

      // 检查用户状态
      if (user.status !== 1) {
        return res.json({
          success: false,
          message: '账户已被禁用，请联系客服'
        });
      }

      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password);
      if (!isPasswordValid) {
        return res.json({
          success: false,
          message: '用户名或密码错误'
        });
      }

      // 更新最后登录时间
      await db.query(
        'UPDATE users SET last_login_at = NOW() WHERE id = ?',
        [user.id]
      );

      // 生成Token
      const token = generateToken(user.id);

      logger.success('用户登录成功', { username: user.username, userId: user.id });

      res.json({
        success: true,
        message: '登录成功',
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            nickname: user.nickname,
            avatar: user.avatar,
            phone: user.phone
          }
        }
      });
    } catch (error) {
      logger.error('用户登录失败', { error: error.message });
      res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }

  // 发送短信验证码
  async sendSmsCode(req, res) {
    try {
      const { phone, type = 'login' } = req.body;

      // 验证手机号格式
      if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
        return res.json({
          success: false,
          message: '请输入正确的手机号'
        });
      }

      // 检查发送频率限制
      const limitCheck = await verificationCodeService.checkSendLimit(phone);
      if (!limitCheck.allowed) {
        return res.json({
          success: false,
          message: limitCheck.message
        });
      }

      // 生成6位验证码
      const codeLength = parseInt(process.env.VERIFICATION_CODE_LENGTH) || 6;
      const code = Math.floor(Math.pow(10, codeLength - 1) + Math.random() * (Math.pow(10, codeLength) - Math.pow(10, codeLength - 1))).toString();

      // 发送短信（使用阿里云短信服务）
      const result = await smsService.sendVerificationCode(
        phone,
        code,
        process.env.SMS_SIGN_NAME,
        process.env.SMS_TEMPLATE_CODE
      );

      if (result.success) {
        // 存储验证码
        const expiresIn = parseInt(process.env.VERIFICATION_CODE_EXPIRES_IN) || 300;
        await verificationCodeService.setVerificationCode(phone, code, type, expiresIn);

        // 存储到数据库（可选，用于统计和审计）
        await db.query(
          `INSERT INTO sms_verification_codes (phone, code, type, expires_at, created_at) 
           VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL ? SECOND), NOW())`,
          [phone, code, type, expiresIn]
        );

        logger.success(`短信验证码发送成功: ${phone}, 类型: ${type}`);

        // 开发环境下打印验证码
        if (process.env.NODE_ENV === 'development') {
          console.log(`📱 验证码: ${code} (${phone})`);
        }

        res.json({
          success: true,
          message: '验证码已发送',
          data: {
            phone,
            expiresIn: parseInt(process.env.VERIFICATION_CODE_EXPIRES_IN) || 300
          }
        });
      } else {
        logger.error(`短信验证码发送失败: ${phone}, 错误: ${result.message}`);
        res.json({
          success: false,
          message: '验证码发送失败，请稍后重试'
        });
      }
    } catch (error) {
      logger.error('发送验证码失败', { error: error.message });
      res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }

  // 短信验证码登录/注册
  async loginWithSms(req, res) {
    try {
      const { phone, code } = req.body;

      // 参数验证
      if (!phone || !code) {
        return res.json({
          success: false,
          message: '手机号和验证码不能为空'
        });
      }

      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        return res.json({
          success: false,
          message: '手机号格式不正确'
        });
      }

      // 验证验证码
      const verifyResult = await verificationCodeService.verifyCode(phone, code);

      if (!verifyResult.success) {
        return res.json({
          success: false,
          message: verifyResult.message
        });
      }

      // 标记验证码为已使用
      await db.query(
        'UPDATE sms_verification_codes SET is_used = 1 WHERE phone = ? AND code = ? AND is_used = 0 ORDER BY created_at DESC LIMIT 1',
        [phone, code]
      );

      // 查询用户是否存在
      let [users] = await db.query(
        'SELECT id, username, nickname, phone, status FROM users WHERE phone = ?',
        [phone]
      );

      let user;
      let isNewUser = false;

      if (users.length === 0) {
        // 用户不存在，自动创建
        const [result] = await db.query(
          `INSERT INTO users (username, phone, nickname, status, created_at, updated_at) 
           VALUES (?, ?, ?, 1, NOW(), NOW())`,
          [phone, phone, phone]
        );

        const userId = result.insertId;
        isNewUser = true;

        // 重新查询用户
        [users] = await db.query(
          'SELECT id, username, nickname, phone, avatar, status FROM users WHERE id = ?',
          [userId]
        );

        user = users[0];
        logger.success('短信登录自动创建用户', { phone, userId });
      } else {
        user = users[0];

        // 检查用户状态
        if (user.status !== 1) {
          return res.json({
            success: false,
            message: '账户已被禁用，请联系客服'
          });
        }
      }

      // 更新最后登录时间
      await db.query(
        'UPDATE users SET last_login_at = NOW() WHERE id = ?',
        [user.id]
      );

      // 生成Token
      const token = generateToken(user.id);

      logger.success('短信登录成功', { phone, userId: user.id, isNewUser });

      res.json({
        success: true,
        message: isNewUser ? '注册并登录成功' : '登录成功',
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            nickname: user.nickname,
            avatar: user.avatar,
            phone: user.phone
          },
          isNewUser
        }
      });
    } catch (error) {
      logger.error('短信登录失败', { error: error.message });
      res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }

  // 游客模式登录（无需微信授权）
  async guestLogin(req, res) {
    try {
      // 生成唯一游客标识（使用时间戳+随机数）
      const guestIdentifier = `GUEST_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

      // 创建游客用户（不依赖openid）
      const guestName = `游客${Date.now().toString().slice(-6)}`;
      const [result] = await db.query(
        `INSERT INTO users (nickname, is_guest, status, created_at, updated_at) 
         VALUES (?, 1, 1, NOW(), NOW())`,
        [guestName]
      );

      const userId = result.insertId;

      // 查询创建的用户
      const [users] = await db.query(
        'SELECT id, username, nickname, phone, is_guest, status FROM users WHERE id = ?',
        [userId]
      );

      const user = users[0];

      // 更新最后登录时间
      await db.query(
        'UPDATE users SET last_login_at = NOW() WHERE id = ?',
        [user.id]
      );

      // 生成Token
      const token = generateToken(user.id);

      logger.success('游客登录成功', { userId: user.id, guestName });

      res.json({
        success: true,
        message: '登录成功',
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            nickname: user.nickname,
            phone: user.phone,
            isGuest: user.is_guest === 1
          },
          isNewUser: true
        }
      });
    } catch (error) {
      logger.error('游客登录失败', { error: error.message });
      res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }

  // 获取当前用户信息
  async getUserInfo(req, res) {
    try {
      const user = req.user;

      res.json({
        success: true,
        data: {
          id: user.id,
          username: user.username,
          nickname: user.nickname,
          phone: user.phone,
          isGuest: user.is_guest === 1
        }
      });
    } catch (error) {
      logger.error('获取用户信息失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 更新用户信息
  async updateUserInfo(req, res) {
    try {
      const userId = req.user.id;
      const { nickname, avatar } = req.body;

      const updates = [];
      const values = [];

      if (nickname) {
        updates.push('nickname = ?');
        values.push(nickname);
      }

      if (avatar) {
        updates.push('avatar = ?');
        values.push(avatar);
      }

      if (updates.length === 0) {
        return res.json({
          success: false,
          message: '没有要更新的信息'
        });
      }

      values.push(userId);

      await db.query(
        `UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`,
        values
      );

      logger.success('更新用户信息成功', { userId });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新用户信息失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 游客转正式用户（绑定手机号）
  async upgradeGuestAccount(req, res) {
    try {
      const userId = req.user.id;
      const { phone, code, username, password } = req.body;

      // 验证手机号
      if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
        return res.json({
          success: false,
          message: '请输入正确的手机号'
        });
      }

      // 验证验证码
      const verifyResult = await verificationCodeService.verifyCode(phone, code);

      if (!verifyResult.success) {
        return res.json({
          success: false,
          message: verifyResult.message
        });
      }

      // 检查手机号是否已被使用
      const [existingUsers] = await db.query(
        'SELECT id FROM users WHERE phone = ? AND id != ?',
        [phone, userId]
      );

      if (existingUsers.length > 0) {
        return res.json({
          success: false,
          message: '该手机号已被其他账号绑定'
        });
      }

      // 更新用户信息
      const updates = ['phone = ?', 'is_guest = 0'];
      const values = [phone];

      if (username) {
        // 检查用户名是否已存在
        const [existingUsernames] = await db.query(
          'SELECT id FROM users WHERE username = ? AND id != ?',
          [username, userId]
        );

        if (existingUsernames.length > 0) {
          return res.json({
            success: false,
            message: '用户名已被使用'
          });
        }

        updates.push('username = ?');
        values.push(username);
      }

      if (password) {
        const hashedPassword = await bcrypt.hash(password, 10);
        updates.push('password = ?');
        values.push(hashedPassword);
      }

      values.push(userId);

      await db.query(
        `UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ?`,
        values
      );

      logger.success('游客账号转正成功', { userId, phone });

      res.json({
        success: true,
        message: '账号升级成功'
      });
    } catch (error) {
      logger.error('游客账号转正失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new UserAuthController();

